package auto.utils;

import auto.base.TestNgSpringContextTests;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.kipa.dubbo.service.DubboService;
import com.kipa.utils.PrintUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author qigui.pan
 * @date 2021/5/18
 * @apiDocUrl
 */


@Component
public class DubboClient extends TestNgSpringContextTests {

    @Autowired
    public DubboService dubboService;

    private final static List<String> EXCEPTION_TYPE = Arrays.asList(
            "ValidationException",
            "IllegalArgumentException"
    );

    public  JSONObject dubbo(String interfaceName, String methodName, String paramType, Object param) {

        Multimap<String, Object> data = ArrayListMultimap.create();
        data.put(paramType, param);

        JSONObject response = new JSONObject();
        try {
            response = JSON.parseObject(dubboService.invoke(
                    interfaceName,
                    methodName,
                    data,
                    "1.0.0"));
            response = response.getJSONObject("responseData");
            Common.removeKey(response,"$..class");
        } catch (Exception e) {

            String exception = e.toString();

            boolean flag = false;
            for (int i = 0; i < EXCEPTION_TYPE.size(); i++) {
                String pattern = String.format("%s:(.*?)[\\r\\n]", EXCEPTION_TYPE.get(i));
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(exception);
                if (m.find()) {
                    response.put("success", false);
                    response.put("msg", m.group(1));
                    PrintUtils.println("====================出参====================");
                    PrintUtils.println(response);
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                throw e;
            }
        }
        return response;
    }


}
